package com.cwj.dragon

import android.Manifest
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Bitmap
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.os.Handler
import android.os.Looper
import android.util.Log
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import com.bumptech.glide.Glide
import com.cwj.dragon.databinding.ActivityMainBinding
import com.cwj.dragon.util.PictureSelectorUtils
import java.io.File
import java.io.FileOutputStream

class MainActivity : AppCompatActivity() {

    private var binding: ActivityMainBinding? = null
    private val mHandler = Handler(Looper.getMainLooper())
    private val codeHead = 201
    private val codeHeadBorder = 202
    private val headBorder = intArrayOf(R.drawable.a1, R.drawable.a2)
    private var i = 0

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding!!.root)
        initView()
    }

    private fun initView() {
        //保存头像
        binding!!.btnSave.setOnClickListener {
            if (ContextCompat.checkSelfPermission(
                    this@MainActivity,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE
                ) != PackageManager.PERMISSION_GRANTED
            ) {
                ActivityCompat.requestPermissions(
                    this@MainActivity,
                    arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE),
                    201
                )
            } else {
                draw
            }
        }

        //更换头像
        binding!!.btnHead.setOnClickListener {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                if (ContextCompat.checkSelfPermission(
                        this@MainActivity,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE
                    ) != PackageManager.PERMISSION_GRANTED
                ) {
                    //没有权限则申请权限
                    ActivityCompat.requestPermissions(
                        this@MainActivity,
                        arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE),
                        202
                    )
                } else {
                    //有权限直接执行
                    chooseHead()
                }
            } else {
                //小于6.0，不用申请权限，直接执行
                chooseHead()
            }
        }

        //更换头像框
        binding!!.btnHeadBorder.setOnClickListener {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                if (ContextCompat.checkSelfPermission(
                        this@MainActivity,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE
                    ) != PackageManager.PERMISSION_GRANTED
                ) {
                    //没有权限则申请权限
                    ActivityCompat.requestPermissions(
                        this@MainActivity,
                        arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE),
                        203
                    )
                } else {
                    //有权限直接执行
                    chooseHeadBorder()
                }
            } else {
                //小于6.0，不用申请权限，直接执行
                chooseHeadBorder()
            }
        }

        //点击头像框更改头像框
        binding!!.ivHeadBorder.setOnClickListener {
            i++
            if (headBorder.size == i) {
                i = 0
            }
            binding!!.ivHeadBorder.setImageResource(headBorder[i])
        }
    }

    private fun chooseHead() {
        PictureSelectorUtils.ofImage(this@MainActivity, codeHead)
    }

    private fun chooseHeadBorder() {
        PictureSelectorUtils.ofImage(this@MainActivity, codeHeadBorder)
    }

    @Deprecated("Deprecated in Java")
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == codeHead && resultCode == RESULT_OK) {
            val head = PictureSelectorUtils.forResult(resultCode, data)
            if (head != null) {
                Glide.with(this).load(head).into(binding!!.ivHead)
            }
        } else if (requestCode == codeHeadBorder && resultCode == RESULT_OK) {
            val headBorder = PictureSelectorUtils.forResult(resultCode, data)
            if (headBorder != null) {
                Glide.with(this).load(headBorder).into(binding!!.ivHeadBorder)
            }
        }
    }

    private val draw: Unit
        get() {
            // 获取图片某布局
            binding!!.rl.isDrawingCacheEnabled = true
            binding!!.rl.buildDrawingCache()
            mHandler.postDelayed({
                // 要在运行在子线程中
                val bmp = binding!!.rl.drawingCache // 获取图片
                savePicture(bmp) // 保存图片
                binding!!.rl.destroyDrawingCache() // 保存过后释放资源
            }, 100)
        }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        when (requestCode) {
            201 -> if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                draw
            } else {
                Toast.makeText(
                    this,
                    "您拒绝了权限的申请，可能无法进行下面的操作哦~",
                    Toast.LENGTH_LONG
                ).show()
            }

            202 -> if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                chooseHead()
            } else {
                Toast.makeText(
                    this,
                    "您拒绝了权限的申请，可能无法进行下面的操作哦~",
                    Toast.LENGTH_LONG
                ).show()
            }

            203 -> if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                chooseHeadBorder()
            } else {
                Toast.makeText(
                    this,
                    "您拒绝了权限的申请，可能无法进行下面的操作哦~",
                    Toast.LENGTH_LONG
                ).show()
            }

            else -> {}
        }
    }

    private fun savePicture(bm: Bitmap) {
        val file = createImageFile()
        //重新写入文件
        try {
            // 写入文件
            val fos = FileOutputStream(file)
            //默认jpg
            bm.compress(Bitmap.CompressFormat.PNG, 100, fos)
            fos.flush()
            fos.close()
            bm.recycle()
            sendBroadcast(Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(file)))
            Toast.makeText(this, "保存成功,请到相册中查看!", Toast.LENGTH_LONG).show()
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    companion object {
        fun createImageFile(): File {
            val dir = File(
                Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
                "Pic"
            )
            if (!dir.exists()) {
                val isSuccess = dir.mkdirs()
                Log.i("Pic", "文件夹创建状态--->$isSuccess")
            }
            return File(dir.path + File.separator + "img_" + System.currentTimeMillis() + ".png")
        }
    }
}